package com.atguigu.interactive;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//判断 干活 通知
//大于两个线程时不可以使用if判断，可能造成虚假唤醒。
//场景---两个线程，一个线程对当前数值加 1，另一个线程对当前数值减 1,  使用线程通信
//wait需要和while配合使用




//这个版本是synchronized  +  wait    +  notifyAll
class number{

    private int number = 0;

    public synchronized void increment() throws InterruptedException {
        while (number != 0){
            this.wait();
        }
        System.out.println(Thread.currentThread().getName()+"\t"+(++number));
        this.notifyAll();
    }

    public synchronized void decrement() throws InterruptedException {
        while (number == 0){
            this.wait();
        }
        System.out.println(Thread.currentThread().getName()+"\t"+(--number));
        this.notifyAll();
    }
}
/**
 * 场景---两个线程，一个线程对当前数值加 1，另一个线程对当前数值减 1,
 * 要求用线程间通信
 */
public class ProdConsumerDemoV1 {
    public static void main(String[] args) {

        number number1 = new number();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    number1.increment();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    number1.decrement();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"B").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    number1.increment();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"C").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    number1.decrement();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"D").start();
    }
}